﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using thousandclear.Data;
using thousandClear.Areas.Admin.Models;

namespace thousandClear.Areas.Admin.Controllers
{
    public class OrderController : BaseController
    {
        // GET: Admin/order
        public ActionResult Index(int? page, int? count, int? status, string sn, 
            int? cType,string cNo,int? cardTy,int? cardMouth,int? addTime,int? auntPer
            ,string richangNo,string richangshengyuNo,string chuanxiangNo,string chuanxiangshengyuNo)
        {
            string level = "1";
            level = GetCookie("level");
            string uid = "1";
            uid = GetCookie("uid");
            ViewBag.level = level;
            ViewBag.uid = uid;
            page = page ?? 1;
            count = count ?? 10;
            int totalCount = 0;
            int totalPage = 1;
            int currentPage = page.Value;
            int pageCount = count.Value;

            List<OrderModel> list = new List<OrderModel>();

            ViewBag.Status = status?.ToString() ?? string.Empty;
            ViewBag.sn = sn?.ToString() ?? string.Empty;
            ViewBag.cType = cType?.ToString() ?? string.Empty;
            ViewBag.cNo = cNo?.ToString() ?? string.Empty;
            ViewBag.cardTy = cardTy?.ToString() ?? string.Empty;
            ViewBag.cardMouth = cardMouth?.ToString() ?? string.Empty;
            ViewBag.addTime = addTime?.ToString() ?? string.Empty;
            ViewBag.auntPer = auntPer?.ToString() ?? string.Empty;
            ViewBag.richangNo = richangNo?.ToString() ?? string.Empty;
            ViewBag.richangshengyuNo = richangshengyuNo?.ToString() ?? string.Empty;
            ViewBag.chuanxiangNo = chuanxiangNo?.ToString() ?? string.Empty;
            ViewBag.chuanxiangshengyuNo = chuanxiangshengyuNo?.ToString() ?? string.Empty;
            
            using (var db = new qianjingEntities())
            {
                var query = db.v_Order.AsQueryable().Where(a => a.RowStatus != 0);

                if (!string.IsNullOrEmpty(status.ToString()))
                {
                    query = query.Where(a => a.RowStatus == status);
                }
                if (!string.IsNullOrEmpty(sn))
                {
                    query = query.Where(a => a.toSerialNo == sn);
                }
                if (!string.IsNullOrEmpty(cType.ToString()))
                {
                    switch (cType.ToString())
                    {
                        case "1":
                            query = query.Where(a => a.ogsDesc != "单项" && a.ogsDesc != "单次");
                            break;
                        case "2":
                            query = query.Where(a => a.ogsDesc == "单次");
                            break;
                        case "3":
                            query = query.Where(a => a.ogsDesc == "单项");
                            break;
                        case "4":
                            query = query.Where(a => a.ogsType == 7);
                            break;
                    }
                }
                if (!string.IsNullOrEmpty(cNo))
                {
                    query = query.Where(a => a.oasNo == cNo);
                }
                if (!string.IsNullOrEmpty(cardTy.ToString()))
                {
                    query = query.Where(a => a.ogsTimeMonth == cardTy);
                }
                if (!string.IsNullOrEmpty(cardMouth.ToString()))
                {
                    query = query.Where(a => a.ogsSignTime == cardMouth);
                }
                if (!string.IsNullOrEmpty(addTime.ToString()))
                {
                    query = query.Where(a => (a.ogsTime - a.ogsTimeMonth * a.ogsSignTime) / a.ogsTimeMonth == addTime);
                }
                if (!string.IsNullOrEmpty(auntPer.ToString()))
                {
                    query = query.Where(a => !string.IsNullOrEmpty(a.toOATID));
                    if (query != null)
                    {
                        query = query.Where(a =>
                           a.toOATID.Contains(auntPer.ToString())
                        );
                    }
                    
                }
                if (!string.IsNullOrEmpty(richangNo))
                {
                    int vv = int.Parse(richangNo);
                    query = query.Where(a => (a.ogsTime - a.ogsSeqNum) <= vv);
                }
                if (!string.IsNullOrEmpty(chuanxiangNo))
                {
                    int vv = int.Parse(chuanxiangNo);
                    query = query.Where(a => a.ogsSeqNum <= vv);
                }


                //TODO:
                if (!string.IsNullOrEmpty(richangshengyuNo))
                {
                    //a.toTime - Convert.ToInt16(a.CreatedBy) <= vv
                    int vv = int.Parse(richangshengyuNo);
                    // query = query.Where(a => (a.toTime - Convert.ToDouble(string.IsNullOrEmpty(a.CreatedBy) ? "0" : a.CreatedBy)) <= vv);

                }
                //TODO:
                if (!string.IsNullOrEmpty(chuanxiangshengyuNo))
                {
                    //a.toTime - Convert.ToInt16(a.CreatedBy) <= vv
                    int vv = int.Parse(chuanxiangshengyuNo);
                    // query = query.Where(a => (a.toTime - Convert.ToDouble(string.IsNullOrEmpty(a.CreatedBy) ? "0" : a.CreatedBy)) <= vv);

                }
                

                totalCount = query.Count();

                var records = query.OrderByDescending(a => a.TOID).Skip((page.Value - 1) * count.Value).Take(count.Value).ToList();

                foreach (var item in records)
                {
                    int time = 0;
                    time = Convert.ToInt16(item.ogsSignTime) * Convert.ToInt16(item.ogsTimeMonth) + Convert.ToInt16(item.toSignTime);
                    string auntName = "";
                    if (!string.IsNullOrEmpty(item.toOATID))
                    {
                        string[] SauntID = item.toOATID.Split(',');
                        foreach (var i in SauntID)
                        {
                            auntName += db.O_Aunt.FirstOrDefault(a => a.OATID.ToString() == i).oatName + "-";
                        }

                    }
                    int yue = int.Parse(item.UpdatedBy==null?"0":item.UpdatedBy.ToString());
                    list.Add(new OrderModel
                    {
                        ogsTime = Convert.ToInt16(item.ogsTime),
                        time = time,
                        toSerialNo = item.toSerialNo,
                        ogsDesc = item.ogsDesc,
                        ocNicName = item.ocNicName,
                        TOID = Convert.ToInt16(item.TOID),
                        toSignTime = Convert.ToInt16(item.toSignTime),
                        toGoodNum = Convert.ToInt16(item.toGoodNum),
                        toTime = Convert.ToInt16(item.toTime),
                        toTotalRate = item.toTotalRate,
                        CreatedDate = item.CreatedDate,
                        UpdatedDate = item.UpdatedDate,
                        RowStatus = item.RowStatus,
                        AuntName = auntName,
                        oasno = item.oasNo,
                        ogsSignTime = Convert.ToInt16(item.ogsSignTime),
                        toSeqNum = Convert.ToInt16(item.CreatedBy),
                        ogsSeqNum = Convert.ToInt16(item.ogsSeqNum),
                        ogsTimeMonth = (int)(item.ogsTimeMonth == null ? 1 : item.ogsTimeMonth),
                        yue = yue,
                        toZengSongLieji = item.toZengSongLieji == null ? 0 : (int)item.toZengSongLieji
                    });
                }


                List<AuntModel> Auntlist = new List<AuntModel>();
                var csm = db.O_Aunt.AsQueryable().OrderByDescending(a => a.OATID).Where(a => a.RowStatus != 2).ToList();

                foreach (var item in csm)
                {
                    Auntlist.Add(new AuntModel
                    {
                        OATID = Convert.ToInt16(item.OATID),
                        oatName = item.oatName,
                        oatPhone = item.oatPhone,
                        oatDesc = item.oatDesc,
                        CreatedDate = item.CreatedDate,
                        RowStatus = item.RowStatus
                    });
                }
                ViewBag.Auntlist = csm;

                List<GoodModel> good = new List<GoodModel>();
                var goodCsm = db.O_Goods.AsQueryable().OrderByDescending(a => a.ogsDesc).Where(a => a.RowStatus == 1).ToList();
                foreach (var item in goodCsm)
                {
                    good.Add(new GoodModel
                    {
                        OGSID = (int)item.OGSID,
                        ogsDesc = item.ogsDesc,
                        ogsSeqNum = (int)(item.ogsSeqNum == null ? 0 : item.ogsSeqNum),
                        ogsTimeMonth = (int)(item.ogsTimeMonth == null ? 0 : item.ogsTimeMonth),
                        ogsArea = item.ogsArea == null ? "" : item.ogsArea,
                        ogsTime = item.ogsTime,
                        ogsSignTime = (int)item.ogsSignTime
                    });
                }
                ViewBag.goodsList = good;

                List<D_item> itli = new List<D_item>();
                var itemList = db.D_item.AsQueryable().Where(a => a.RowStatus == 1).ToList();
                foreach (var item in itemList)
                {
                    itli.Add(new D_item()
                    {
                        DIMID = (int)item.DIMID,
                        dimDesc = item.dimDesc
                    });
                }
                ViewBag.itlist = itli;
            }

            ViewBag.TotalCount = totalCount;
            totalPage = int.Parse((totalCount / count).ToString()) + (totalCount % count == 0 ? 0 : 1);
            ViewBag.TotalPage = totalPage;
            ViewBag.CurrentPage = currentPage;
            ViewBag.PageCount = pageCount;

            return View(list);
        }
        // GET: Admin/Detail
        public ActionResult Detail(string toSerialNo)
        {
            OrderModel model = new OrderModel();
            List<OrderLogModel> tlog = new List<OrderLogModel>();

            using (var db = new qianjingEntities())
            {
                var query = db.v_Order.AsQueryable();

                var records = query.FirstOrDefault(a => a.toSerialNo == toSerialNo);
                string SignDetail = "";
                if (!string.IsNullOrEmpty(records.toItemsGift))
                {
                    if (records.toItemsGift.Trim() != "")
                    {
                        string[] SauntID = records.toItemsGift.Split(',');
                        foreach (var i in SauntID)
                        {
                            SignDetail += db.D_item.FirstOrDefault(a => a.DIMID.ToString() == i).dimDesc + "-";
                        }
                    }
                    

                }
                if (records != null)
                {
                    model.oasName = records.oasName;
                    model.toRemark = records.toRemark;
                    model.toSerialNo = records.toSerialNo;
                    model.ogsDesc = records.ogsDesc;
                    model.ocNicName = records.ocNicName;
                    model.oasName = records.ocNicName;
                    model.TOID = Convert.ToInt16(records.TOID);
                    model.toSignTime = Convert.ToInt16(records.toSignTime);
                    model.toGoodNum = Convert.ToInt16(records.toGoodNum);
                    model.toTime = Convert.ToInt16(records.toTime);
                    model.area = records.ogsArea;
                    model.toTotalRate = records.toTotalRate;
                    model.CreatedDate = records.CreatedDate;
                    model.UpdatedDate = records.UpdatedDate;
                    model.osaPhone = records.osaPhone;
                    model.osaTimeslot = records.osaTimeslot;
                    model.startDay = records.osaStartDay;
                    model.endDay = records.osaEndDay;
                    model.SignDetail = string.IsNullOrEmpty(SignDetail)?"暂无": SignDetail;
                    model.oasAddressDetail = records.datDesc + records.datDesc1 + records.datDesc2 + records.oasAddressDetail;

                }
                var ves = db.T_OrderLog.OrderByDescending(a => a.CreatedDate).Where(a => a.tilTOID == records.TOID && a.RowStatus == 1);
                foreach (var item in ves)
                {
                    var itemdesc = db.D_item.FirstOrDefault(a => a.DIMID == item.tilDIID);
                    string aunt = "";
                    string[] s = item.tilOAID.ToString().Split(new char[] { ',' });
                    if (s.Length > 0)
                    {
                        for (int i = 0; i < s.Length; i++)
                        {
                            string f = s[i];
                            var AuntName = db.O_Aunt.FirstOrDefault(a => a.OATID.ToString() == f).oatName;
                            aunt += AuntName;
                        }
                    }
                    tlog.Add(new OrderLogModel
                    {
                        TOLID = Convert.ToInt16(item.TOLID),
                        tilDIID = item.tilDIID,
                        dimDesc = item.tilDIID == 1 ? "日常服务" : "专项服务",
                        CreatedDate = item.CreatedDate,
                        oatName = aunt,
                    });
                }

            }


            ViewBag.tlog = tlog;


            return View(model);
        }
        // GET: Admin/order
        [HttpGet]
        public int giveAunt(string order,string aunt)
        {

            using (var db = new qianjingEntities())
            {

                var query = db.T_Order.FirstOrDefault(a => a.toSerialNo == order);
                query.RowStatus = 5;

                query.toOATID = aunt;

                db.SaveChanges();
            }
            return 1;

        }

        // var data1 = '{"txtNos":"'+$("#txtNos").val()+'","txtP":"'+$("#txtP").val()+'","txtRate":"'+$("#txtRate").val()+'","txtDate":"'+$("#txtDate").val()+'","txtTime":"'+$("#txtTime").val()+'"}';$("#txtTime").val()+'","txtrichang":"'+$("#txtrichang").val()+'","txtzhuanxiang":"'+$("#txtzhuanxiang").val()+'"}';
        [HttpPost]
        public string CreateOrder(string txtNos, string txtP, string txtRate, string txtDate, string txtTime,string txtrichang,string txtzhuanxiang)
        {
            using (var db = new qianjingEntities())
            {
                string Number = DateTime.Now.ToString("yyMMddHHmmss");
                Random example = new Random();
                int Numradom = example.Next(10000, 99999);
                Number = Number + Numradom.ToString();

                int ogid = int.Parse(txtP);
                decimal total = decimal.Parse(txtRate);

                var OAID = db.O_Address.FirstOrDefault(oo => oo.oasNo == txtNos && oo.RowStatus == 1);
                var good = db.O_Goods.FirstOrDefault(og => og.OGSID == ogid);

                DateTime temp = DateTime.Parse(txtDate);
                string startDay = temp.ToString("yyyyMMdd");
                int zengsong = 0;
                if (good.ogsTimeMonth > 1)
                {
                    zengsong = (int)(((good.ogsTime - good.ogsTimeMonth * good.ogsSignTime) / good.ogsTimeMonth) < 0 ? 0 : ((good.ogsTime - good.ogsTimeMonth * good.ogsSignTime) / good.ogsTimeMonth));
                }

                if (good.ogsTimeMonth <= 1)
                {
                    zengsong = 0;
                }


                string endDay = temp.AddMonths((zengsong + (int)good.ogsSignTime)).ToString("yyyyMMdd");
                int txtrichang1 = int.Parse(txtrichang);
                int txtzhuanxiang1 = int.Parse(string.IsNullOrEmpty(txtzhuanxiang) ? "0" : txtzhuanxiang);
                db.T_Order.Add(new T_Order
                {
                    toSerialNo = Number,
                    toOAID = (int)(OAID == null ? 0 : OAID.OASID),
                    toOGID = ogid,
                    toTotalRate = total,
                    toGoodNum = 1,
                    toTime = txtrichang1,
                    toSignTime = good.ogsSignTime,
                    RowStatus = 1,
                    CreatedDate = DateTime.Now,
                    CreatedBy = txtzhuanxiang1.ToString()
                    
                });


                var ttemp = db.O_Address.FirstOrDefault(oad => oad.oasNo == txtNos);
                ttemp.osaEndDay = endDay;
                ttemp.osaStartDay = startDay;
                ttemp.osaTimeslot = txtTime;

                db.SaveChanges();
            }
            return "1";
        }


        [HttpPost]
        public string GetDetailOrder(string order)
        {
            OrderModel model = new OrderModel();

            using (var db = new qianjingEntities())
            {
                var query = db.v_Order.AsQueryable();

                var records = query.FirstOrDefault(a => a.TOID.ToString().Trim() == order.Trim());
                string SignDetail = "";
                if (!string.IsNullOrEmpty(records.toItemsGift))
                {
                    if (records.toItemsGift.Trim() != "")
                    {
                        string[] SauntID = records.toItemsGift.Split(',');
                        foreach (var i in SauntID)
                        {
                            SignDetail += db.D_item.FirstOrDefault(a => a.DIMID.ToString() == i).dimDesc + "-";
                        }
                    }


                }
                if (records != null)
                {
                    model.oasName = records.oasName;
                    model.toRemark = records.toRemark;
                    model.toSerialNo = records.toSerialNo.ToString().Trim();
                    model.ogsDesc = records.ogsDesc;
                    model.ocNicName = records.ocNicName;
                    model.oasName = records.ocNicName;
                    model.TOID = Convert.ToInt16(records.TOID);
                    model.toSignTime = Convert.ToInt16(records.toSignTime);
                    model.toGoodNum = Convert.ToInt16(records.toGoodNum);
                    model.toTime = Convert.ToInt16(records.toTime);
                    model.area = records.ogsArea;
                    model.toTotalRate = records.toTotalRate;
                    model.CreatedDate = records.CreatedDate;
                    model.UpdatedDate = records.UpdatedDate;
                    model.osaPhone = records.osaPhone;

                    if (string.IsNullOrEmpty(records.osaTimeslot))
                    {
                        model.osaTimeslot = "00:00";
                    }
                    else
                    {
                        model.osaTimeslot = records.osaTimeslot.ToString().Split(':').ElementAt(0).Length > 1 ? records.osaTimeslot.Trim() : "0" + records.osaTimeslot.Trim();
                    }
                    
                    string daytime = "";

                    if (string.IsNullOrEmpty(records.osaStartDay))
                    {
                        daytime = "";
                    }
                    else
                    {
                        daytime = records.osaStartDay.Substring(0, 4) + "-";
                        daytime += records.osaStartDay.Substring(4, 2) + "-";
                        daytime += records.osaStartDay.Substring(6, 2);
                    }

                    string enddaytime = "";

                    if (string.IsNullOrEmpty(records.osaEndDay))
                    {
                        enddaytime = "";
                    }
                    else
                    {
                        enddaytime = records.osaEndDay.Substring(0, 4) + "-";
                        enddaytime += records.osaEndDay.Substring(4, 2) + "-";
                        enddaytime += records.osaEndDay.Substring(6, 2);
                    }

                    model.startDay = daytime;
                    model.endDay = enddaytime;
                    model.SignDetail = string.IsNullOrEmpty(SignDetail) ? "暂无" : SignDetail;
                    model.oasAddressDetail = records.datDesc + records.datDesc1 + records.datDesc2 + records.oasAddressDetail;
                    model.oasno = records.oasNo;
                    model.toOGID = (int)records.toOGID;
                    model.a = string.IsNullOrEmpty(records.CreatedBy) ? 0 : int.Parse(records.CreatedBy);
                    model.RowStatus = records.RowStatus;
                }
                

            }

            return JsonConvert.SerializeObject(model);
        }

        [HttpPost]
        public string UpdateOrder(string orderid, string txtNos, string txtP, string txtRate, string txtDate, string txtTime, string txtrichang, string txtzhuanxiang, string txtEndDate,string txStatus)
        {
            using (var db = new qianjingEntities())
            {
                //var OAID = db.O_Address.FirstOrDefault(oo => oo.oasNo == txtNos && oo.RowStatus == 1);
                int ogid = int.Parse(txtP);
                decimal total = decimal.Parse(txtRate);
                var good = db.O_Goods.FirstOrDefault(og => og.OGSID == ogid);
                int txtrichang1 = int.Parse(txtrichang);
                int txtzhuanxiang1 = int.Parse(string.IsNullOrEmpty(txtzhuanxiang) ? "0" : txtzhuanxiang);
                byte st = byte.Parse(txStatus);

                var query = db.T_Order.FirstOrDefault(od => od.TOID.ToString().Trim() == orderid.ToString().Trim());
                
                query.toOGID = ogid;
                query.toTotalRate = total;
                query.toGoodNum = 1;
                query.toTime = txtrichang1;
                query.toSignTime = good.ogsSignTime;
                query.CreatedBy = txtzhuanxiang1.ToString();
                query.RowStatus = st;

                db.SaveChanges();

                int zengsong = 0;
                if (good.ogsTimeMonth > 1)
                {
                    zengsong = (int)(((good.ogsTime - good.ogsTimeMonth * good.ogsSignTime) / good.ogsTimeMonth) < 0 ? 0 : ((good.ogsTime - good.ogsTimeMonth * good.ogsSignTime) / good.ogsTimeMonth));
                }

                if (good.ogsTimeMonth <= 1)
                {
                    zengsong = 0;
                }

                DateTime temp = DateTime.Parse(txtDate);
                string startDay = temp.ToString("yyyyMMdd");

                DateTime temp1 = DateTime.Parse(txtEndDate);
                string endDay = temp1.ToString("yyyyMMdd");

                var ttemp = db.O_Address.FirstOrDefault(oad => oad.OASID == query.toOAID);
                if (ttemp != null)
                {
                    if (st==1 && ttemp.oasNo == null)
                    {
                        ttemp.oasNo = db.SP_GetRefNo().FirstOrDefault();
                    }

                    ttemp.osaEndDay = endDay;
                    ttemp.osaStartDay = startDay;
                    ttemp.osaTimeslot = txtTime;
                }
                

                db.SaveChanges();

            }
            return "1";
        }

        [HttpPost]
        public string GoToContiun(string orderid, string txtNos, string txtP, string txtRate, string txtDate, string txtTime, string txtrichang, string txtzhuanxiang)
        {
            using (var db = new qianjingEntities())
            {
                var OAID = db.O_Address.FirstOrDefault(oo => oo.oasNo == txtNos && oo.RowStatus == 1);
                int ogid = int.Parse(txtP);
                decimal total = decimal.Parse(txtRate);

                var good = db.O_Goods.FirstOrDefault(og => og.OGSID == ogid);
                int txtrichang1 = int.Parse(txtrichang);
                int txtzhuanxiang1 = int.Parse(string.IsNullOrEmpty(txtzhuanxiang) ? "0" : txtzhuanxiang);

                var query = db.T_Order.FirstOrDefault(od => od.TOID.ToString().Trim() == orderid.ToString().Trim());
                
                //把之前订单的日常总次数存储到UpdateBy
                var sstt = db.O_Goods.FirstOrDefault(og => og.OGSID == query.toOGID);
                query.UpdatedBy = (int.Parse(string.IsNullOrEmpty(query.UpdatedBy)?"0": query.UpdatedBy) + sstt.ogsTime).ToString();
                //把之前订单的专项总次数存储到toZengSongLieji
                query.toZengSongLieji = (query.toZengSongLieji == null ? 0 : query.toZengSongLieji) + sstt.ogsSeqNum;


                query.toOGID = ogid;
                query.toTotalRate = total;
                query.toGoodNum = 1;



                query.toTime = txtrichang1 + good.ogsTime;
                query.toSignTime = good.ogsSignTime;
                query.CreatedBy = (int.Parse(txtzhuanxiang1.ToString()) + good.ogsSeqNum).ToString();

                db.SaveChanges();









                int zengsong = 0;
                if (good.ogsTimeMonth > 1)
                {
                    zengsong = (int)(((good.ogsTime - good.ogsTimeMonth * good.ogsSignTime) / good.ogsTimeMonth) < 0 ? 0 : ((good.ogsTime - good.ogsTimeMonth * good.ogsSignTime) / good.ogsTimeMonth));
                }

                if (good.ogsTimeMonth <= 1)
                {
                    zengsong = 0;
                }

                DateTime temp = DateTime.Parse(txtDate);
                string startDay = temp.ToString("yyyyMMdd");
                string endDay = temp.AddMonths((zengsong + (int)good.ogsSignTime)).ToString("yyyyMMdd");

                var ttemp = db.O_Address.FirstOrDefault(oad => oad.oasNo == txtNos);
                ttemp.osaEndDay = endDay;
                ttemp.osaStartDay = startDay;
                ttemp.osaTimeslot = txtTime;

                db.SaveChanges();

            }
            return "1";
        }

        [HttpPost]
        public void RemoveOrder(string orderid)
        {
            using (var db = new qianjingEntities())
            {
                var query = db.T_Order.FirstOrDefault(od => od.TOID.ToString().Trim() == orderid.ToString().Trim());

                query.RowStatus = 0;

                db.SaveChanges();
            }
        }
    }
}